package bgplite.sim;

import java.util.*;
import java.io.*;

import bgplite.io.*;
import bgplite.threading.BGPMaster;
import bgplite.topo.AS;

public class BGPLite {
	
	private static final boolean DEBUG = false;

	public static void main(String[] args) throws IOException {

		long startTime, endTime;
		String asRelFile, ipCountFile, vitalASFile;
		HashMap<Integer, AS> liveTopo, prunedTopo;

		if (args.length < 3) {
			System.out.println("Usage: ./BGPLite <as rel file> <ip count file> <vital as file>");
			return;
		}

		startTime = System.currentTimeMillis();
		asRelFile = args[0];
		ipCountFile = args[1];
		vitalASFile = args[2];

		/*
		 * Build base topology objects
		 */
		ASTopoParser asTopoParsingEngine = new ASTopoParser(asRelFile, ipCountFile, vitalASFile);
		liveTopo = asTopoParsingEngine.getActiveTopology();
		prunedTopo = asTopoParsingEngine.getPrunedTopology(); 
		
		/*
		 * Serialization control
		 */
		SerializationMaster serialControl = new SerializationMaster(asRelFile, ipCountFile, vitalASFile);
		if (serialControl.hasValidBGPSerialFile()) {
			System.out.println("Valid serial file exists, skipping fresh build.");
			serialControl.loadBGPSerialFile(liveTopo);
			System.out.println("Topology loaded from serial file.");
		} else {
			System.out.println("No serial file exists, building topology from scratch.");
			BGPMaster.buildBGPConnection(liveTopo);
			System.out.println("Topo built and BGP converged.");
			serialControl.buildBGPSerialFile(liveTopo);
			System.out.println("Topology saved to serial file.");
		}

		if (BGPLite.DEBUG) {
			System.out.println("liveTopo:");
			for (AS tAS : liveTopo.values()) {
				System.out.println(tAS.getASN());
			}
			System.out.println("prunedTopo:");
			for (AS tAS : prunedTopo.values()) {
				System.out.println(tAS.getASN());
			}

			System.out.println("live ip count:");
			for (AS tAS : liveTopo.values())
				System.out.println(tAS.getASN() + ", " + tAS.getIPCount());
			System.out.println("pruned ip count:");
			for (AS tAS : prunedTopo.values())
				System.out.println(tAS.getASN() + ", " + tAS.getIPCount());

			System.out.println("routing tables:");
			for (AS tAS : liveTopo.values()) {
				System.out.println(tAS.printDebugString());
			}
		}
		
		endTime = System.currentTimeMillis();
		System.out.println("\nAll work done, this took: " + (endTime - startTime) / 60000 + " minutes.");

	}
}
